/* $Id: CategoryListActivity.java 89 2008-01-22 02:38:52Z osborn.steven $
 * 
 * Undroid Package Manager
 *
 * Copyright 2007 Steven Osborn
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */
package com.bitsetters.undroid;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.ListActivity;
import android.app.NotificationManager;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;

import com.bitsetters.undroid.common.CommonMenu;
import com.bitsetters.undroid.common.Footer;
import com.bitsetters.undroid.common.RR;
import com.bitsetters.undroid.exception.RepoException;
import com.bitsetters.undroid.helpers.DbHelper;
import com.bitsetters.undroid.helpers.RepoReader;

/**
 * 
 * 
 * @author Steven Osborn - http://steven.bitsetters.com
 */
public class CategoryListActivity extends ListActivity {

    public static final String TAG = "UNDROID[CategoryList]";
    public static final int CATEGORY_LOAD_ERROR = 100;
    public static final String KEY_CATID = "catid";
    public static final String KEY_APPID = "appid";
    public static final String CATEGORY_FILE = "categories.xml";
    private List<Category> categories;
    private DbHelper mDb;

    public static List<Category> items; 

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        mDb = new DbHelper(this);


        requestWindowFeature(Window.FEATURE_PROGRESS);

        setContentView(R.layout.list);

        getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
                Window.PROGRESS_INDETERMINATE_ON);

        getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
                Window.PROGRESS_VISIBILITY_ON);



//      Intent i = new Intent();
//      i.setClass(this, SyncService.class);
//      this.startService(i,null);

        RepoReader rr = new RepoReader(this,mDb);
        try {
            rr.getRepo(RepoReader.UNDROID_REPO);
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (RepoException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }


        items  = new ArrayList<Category>();


        try {
            items = getCategoryList();
        } catch(Exception e) {
            Log.e(TAG,e.toString());

            // Could not load categories xml, notify user
            NotificationManager nm = (NotificationManager)
            getSystemService(NOTIFICATION_SERVICE);
            nm.notifyWithText(CATEGORY_LOAD_ERROR,
                    getText(R.string.category_load_error),
                    NotificationManager.LENGTH_SHORT, null);
        }

        TextView tv = (TextView) findViewById(R.id.empty_list);

        try {
            CategoryListAdapter btla = new CategoryListAdapter(this);
            btla.setListItems(items);
            setListAdapter(btla);
        } catch (IndexOutOfBoundsException e) {
            tv.setVisibility(View.VISIBLE);
            tv.setText("Repository Empty.");
        }

        getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
                Window.PROGRESS_INDETERMINATE_OFF);

        getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
                Window.PROGRESS_VISIBILITY_OFF);



        Footer.setup(this);
    }

    /**
     * 
     * @param location
     * @throws XmlPullParserException
     * @throws IOException
     */
    public void readRepo(String location) 
    throws XmlPullParserException, IOException {

        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        XmlPullParser xpp = factory.newPullParser();

        URL u = new URL(location);
        InputStream in = u.openStream();
        xpp.setInput(in, "ISO-8859-1");

        int eventType = xpp.getEventType();
        String currentText = "";

        while (eventType != XmlPullParser.END_DOCUMENT) {
            if(eventType == XmlPullParser.START_TAG) {
            } else if(eventType == XmlPullParser.END_TAG) {
            } else if(eventType == XmlPullParser.TEXT) {
                currentText += xpp.getText();
            }
            eventType = xpp.next();
        }
        return;
    }

    /**
     * 
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        return CommonMenu.createMenu(this, menu);
    }

    /**
     * 
     */
    @Override
    public boolean onOptionsItemSelected(Menu.Item item) {
        return CommonMenu.handleOption(item);
    }

    /**
     * 
     */
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Intent i = new Intent(this, ProgramListActivity.class);
        i.putExtra(KEY_CATID, items.get(position).getCategoryId());
        startActivity(i);
    }

    /**
     * 
     */
    @Override
    protected void onPause() {
        super.onPause();
        mDb.close();
        mDb = null;
    }

    /**
     * 
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (mDb == null) {
            mDb = new DbHelper(this);
        }
    }

    /**
     * Parses categories.xml and returns a list of Category objects. 
     *  
     * @param xpp
     * @return
     * @throws XmlPullParserException
     * @throws IOException
     */
    public List<Category> getCategoryList() 
    throws XmlPullParserException, IOException {
        XmlPullParser xpp = getResources().getXml(R.xml.categories);
        categories = new ArrayList<Category>();
        int eventType = xpp.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            if(eventType == XmlPullParser.START_TAG) {
                if(xpp.getName().compareTo("category") == 0) {
                    int currentCount = mDb.getCategoryCount(
                            Integer.valueOf(xpp.getAttributeValue(null,"id")));
                    if(currentCount > 0) {
                        Drawable categoryIcon =  RR.getDrawable(this,
                                xpp.getAttributeValue(null,"icon"));
                        String categoryName = RR.getString(this,
                                xpp.getAttributeValue(null,"string"));
                        Category c = new Category(categoryName, categoryIcon,currentCount);
                        c.setCategoryId(Integer.valueOf(xpp.getAttributeValue(null,"id")));
                        categories.add(c);
                    }
                }
            }
            eventType = xpp.next();
        }
        return categories;
    }
}
